package utils;

import lombok.AccessLevel;
import lombok.NoArgsConstructor;
import org.apache.commons.collections.CollectionUtils;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

/**
 * @author yaosongbing
 * @className com.bestpay.o2o.nearby.service.common.util.CollectionUtil
 * @desc
 * @createTime 2020/7/1 16:49
 */
@NoArgsConstructor(access = AccessLevel.PRIVATE)
public class CollectionUtil {


    /**
     * 集合拆分
     * 小于等于limit不需要拆分
     *
     * @param list
     * @param limit
     * @param <E>
     * @return
     */
    public static <E> List<List<E>> splitList(List<E> list, final int limit) {
        if ( CollectionUtils.isEmpty(list)) {
            return Collections.emptyList();
        }

        final int listSize = list.size();
        final int count = listSize % limit == 0 ? listSize / limit : listSize / limit + 1;

        final List<List<E>> result = new ArrayList<>(count);

        if (listSize <= limit) {
            result.add(list);
            return result;
        }

        List<E> subList = null;
        for (int i = 0; i < count; i++) {
            subList = (i == count - 1) ? list.subList(i * limit, listSize)
                    : list.subList(i * limit, (i + 1) * limit);
            result.add(subList);
        }

        return result;
    }
}
